export function parentToTree(
  items: any[],
  parentid = 0,
  labelMap: string = '',
  childrenNameKey = 'children',
  parentKey = 'parentId',
  idKey = 'id'
) {
  const children = items.filter((i) => i[parentKey] == parentid);

  return children.map((child) => {
    const childObj: any = { ...child };
    childObj['key'] = labelMap ? String(child[idKey]) : child[idKey];
    if (labelMap) {
      childObj['label'] = child[labelMap];
      childObj['value'] = child[idKey];
    }

    const hasChildren = items.some((s) => s[parentKey] == child[idKey]);
    if (hasChildren) {
      childObj[childrenNameKey] = parentToTree(
        items,
        child[idKey],
        labelMap,
        childrenNameKey,
        parentKey,
        idKey
      );
    }

    return childObj;
  });
}

export function fileImageToCanvas(file: File): Promise<HTMLCanvasElement> {
  return new Promise((resolve) => {
    try {
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onloadend = (e: any) => {
        var image = new Image(); // Creates image object
        image.src = e.target.result; // Assigns converted image to image object
        image.onload = (ev) => {
          var canvas = document.createElement('canvas'); // Creates a canvas object
          var context = canvas.getContext('2d'); // Creates a contect object
          canvas.width = image.width; // Assigns image's width to canvas
          canvas.height = image.height; // Assigns image's height to canvas
          canvas.style.width = image.width + 'px';
          canvas.style.height = image.height + 'px';
          context!.drawImage(image, 0, 0); // Draws the image on canvas

          return resolve(canvas);
        };
      };
    } catch (e) {
      Promise.reject(e);
    }
  });
}
